package com.itfitness.mchart.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.chat.EMGroupManager;
import com.hyphenate.chat.EMGroupOptions;
import com.hyphenate.easeui.domain.EaseUser;
import com.itfitness.mchart.R;
import com.itfitness.mchart.bean.ChoiceContactItemBean;
import com.itfitness.mchart.utils.ListUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * 创建群组选择联系人界面
 */
public class GroupChoiceContactActivity extends BaseActivity {

    @BindView(R.id.activity_group_choice_contact_rv)
    RecyclerView activityGroupChoiceContactRv;
    private BaseQuickAdapter<ChoiceContactItemBean, BaseViewHolder> mBaseQuickAdapter;
    private ArrayList<ChoiceContactItemBean> allContacts;

    @Override
    protected int LayoutRes() {
        return R.layout.activity_group_choice_contact;
    }

    @Override
    protected boolean isHaveTitle() {
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        initDatas();
    }

    private void initDatas() {
        setTitle("选择联系人",R.color.colorTitleText);
        setRightTitle("保存", R.color.colorTitleText, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//              创建群组
                createGroup();
            }
        });
        activityGroupChoiceContactRv.setLayoutManager(new LinearLayoutManager(this));
        initContactList();
    }

    /**
     * 创建群组
     */
    private void createGroup() {
        final String[] choiceContacts = getChoiceContacts();
        Intent intent = getIntent();
        final String groupname = intent.getStringExtra("groupname");
        final String groupdesc = intent.getStringExtra("groupdesc");

        final boolean ispublic = intent.getBooleanExtra("ispublic", false);
        final boolean isinvite = intent.getBooleanExtra("isinvite", false);
        Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> emitter) throws Exception {
                EMGroupOptions option = new EMGroupOptions();
                option.maxUsers = 200;
                if(ispublic){
                    if(isinvite){
                        option.style = EMGroupManager.EMGroupStyle.EMGroupStylePublicOpenJoin ;
                    }else {
                        option.style = EMGroupManager.EMGroupStyle.EMGroupStylePublicJoinNeedApproval;
                    }
                }else {
                    if(isinvite){
                        option.style = EMGroupManager.EMGroupStyle.EMGroupStylePrivateMemberCanInvite;
                    }else {
                        option.style = EMGroupManager.EMGroupStyle.EMGroupStylePrivateOnlyOwnerInvite;
                    }
                }
                EMClient.getInstance().groupManager().createGroup(groupname, groupdesc, choiceContacts, "邀您加入群", option);
                emitter.onNext(1);
            }
        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Integer>() {
                    @Override
                    public void accept(Integer integer) throws Exception {
                        if (integer == 1) {
                            ToastUtils.showShort("建群成功");
                            gotoActivity(GroupActivity.class);
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        LogUtils.eTag("注册", throwable.getMessage());
                        ToastUtils.showShort("建群失败，请重试");
                    }
                });

    }

    /**
     * 获取选择的联系人
     */
    private String[] getChoiceContacts() {
        ArrayList<String> choiceCotacts = new ArrayList<>();
        for(ChoiceContactItemBean choiceContactItemBean:allContacts){
            if(choiceContactItemBean.isIschoice()){
                choiceCotacts.add(choiceContactItemBean.getUsername());
            }
        }
        String[] strings = new String[choiceCotacts.size()];
        choiceCotacts.toArray(strings);
        return strings;
    }

    /**
     * 加载联系人列表
     */
    private void initContactList() {
        Observable.create(new ObservableOnSubscribe<List<String>>() {
            @Override
            public void subscribe(ObservableEmitter<List<String>> emitter) throws Exception {
                List<String> allContactsFromServer = EMClient.getInstance().contactManager().getAllContactsFromServer();
                emitter.onNext(allContactsFromServer);
            }
        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<List<String>>() {
                    @Override
                    public void accept(List<String> allContactsFromServer) throws Exception {
                        if (allContactsFromServer != null && allContactsFromServer.size()>0) {
                            allContacts = new ArrayList<>();
                            for (String username:allContactsFromServer){
                                ChoiceContactItemBean choiceContactItemBean = new ChoiceContactItemBean(username);
                                allContacts.add(choiceContactItemBean);
                            }
                            initAdapter(allContacts);
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        LogUtils.eTag("获取联系人", throwable.getMessage());
                        ToastUtils.showShort("获取联系人失败");
                    }
                });
    }

    private void initAdapter(ArrayList<ChoiceContactItemBean> choiceContacts) {
        if(mBaseQuickAdapter == null){
            mBaseQuickAdapter = new BaseQuickAdapter<ChoiceContactItemBean, BaseViewHolder>(R.layout.item_choicecontact,choiceContacts) {
                @Override
                protected void convert(BaseViewHolder helper, final ChoiceContactItemBean item) {
                    helper.setText(R.id.item_invitenotify_tv_name,item.getUsername());
                    helper.setOnCheckedChangeListener(R.id.item_choicecontact_cb, new CompoundButton.OnCheckedChangeListener() {
                        @Override
                        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                            item.setIschoice(isChecked);
                        }
                    });
                }
            };
            mBaseQuickAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    CheckBox checkBox = view.findViewById(R.id.item_choicecontact_cb);
                    checkBox.setChecked(!checkBox.isChecked());
                    mBaseQuickAdapter.getData().get(position).setIschoice(checkBox.isChecked());
                }
            });
            activityGroupChoiceContactRv.setAdapter(mBaseQuickAdapter);
        }else {
            mBaseQuickAdapter.setNewData(choiceContacts);
            mBaseQuickAdapter.notifyDataSetChanged();
        }

    }
}
